<?php
/**
 * created by zzy
 * date: 2018/1/26 14:07
 */


namespace App\Api\Service\Waste\Controllers;


use App\Eloquent\Area;
use App\Eloquent\City;
use App\Eloquent\Province;
use App\Eloquent\Ygt\DepartmentUser;
use App\Eloquent\Ygt\OrdertypeProcessWaste;
use App\Eloquent\Ygt\Product;
use App\Eloquent\Ygt\ProductFields;
use App\Eloquent\Ygt\User;
use App\Eloquent\Ygt\Waste;
use App\Eloquent\Ygt\WasteBuyer;
use App\Eloquent\Ygt\WasteWater;
use App\Engine\Func;
use Framework\BaseClass\Api\Controller;

class WaterController extends Controller
{
    public $userId        = 25;

    public function getWaterList(){
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );
        $companyId          = $userInfo->company_id;
        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $date          = request('date','');
        $page          = request('page',1);


        //取材料的流水
        $limit          = 10;
        $offset         = ($page - 1) * $limit;

        $WasteWaterObj = new WasteWater();
        if(!empty($date)){
            $startTime = strtotime($date);
            $endTime = $startTime+24*3600;

            $WasteWaterObj = $WasteWaterObj->whereBetween('ygt_waste_water.created_at',[$startTime,$endTime]);
        }
        //2019-01-23 Linwei  增加本厂限制
        $WasteWaterObj->where("company_id","=",$companyId);
        //获得总数
        $count = $WasteWaterObj->count();

        //获得数据
        $lists = $WasteWaterObj->leftJoin('ygt_waste','ygt_waste.id','=','ygt_waste_water.waste_id')
            ->leftJoin('ygt_user','ygt_user.id','=','ygt_waste_water.uid')
            ->skip($offset)->take($limit)
            ->orderBy('created_at','desc')
            ->get([
                'ygt_waste_water.id',
                'ygt_waste_water.type',
                'ygt_waste_water.number',
                'ygt_waste_water.residual_number',
                'ygt_waste_water.created_at',
                'ygt_waste.waste_name as name',
                'ygt_user.truename as operate_name'
            ])
            ->toArray();

        //修改时间显示格式
        foreach ($lists as $key => $tmpRow){
            $lists[$key]['created_time'] = date('Y-m-d H:i:s',$tmpRow['created_at']);
            $lists[$key]['sn'] = '';
            if($tmpRow['type'] == 1){
                $lists[$key]['type_name'] = '已入库-订单';
                $lists[$key]['type_color'] = '#00CAB3';
            }
            else if($tmpRow['type'] == 2){
                $lists[$key]['type_name'] = '已出库-废料卖出';
                $lists[$key]['type_color'] = '#FFB500';
            }
            else{
                $lists[$key]['type_name'] = '异常数据';
                $lists[$key]['type_color'] = '#FFB500';
            }
        }

        $listData           = [
            'list'=>$lists,
        ];
        $pagingData         = [
            'page' => $page,
            'pageSize' => $limit,
            'total' => $count,
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }


    public function index()
    {
        $userId             = Func::getHeaderValueByName( 'userid',$this->userId );
        $userInfo           = DepartmentUser::getCurrentInfo( $userId );

        $wasteRelateType = request('relate_type');
        $wasteRelateId = request('relate_id');

        if(!$userInfo)
        {
            xThrow(ERR_PARAMETER,'登录失败');
        }
        $companyId          = $userInfo->company_id;
        $wasteId            = request('id',0);
        $limit              = request('limit',20);
        $page               = request('page',1);
        $offset             = ($page-1)*$limit;


        if($wasteRelateType && $wasteRelateId){
            if(strstr($wasteRelateId,'A')){
                //集合材料取集合材料下的第一个sku材料
                $tmpAssemblageMaterialId = str_replace('A','',$wasteId);
                $materialRow = \App\Eloquent\Ygt\product::where(['assemblage_material_id'=>$tmpAssemblageMaterialId])->first();
                $wasteRelateId = $materialRow['id'];
            }

            $tmpWasteRow = \App\Eloquent\Ygt\Waste::where(['relate_type'=>1,'relate_id'=>$wasteRelateId])->first();
            $wasteId = $tmpWasteRow['id'];
        }


        if (!$wasteId)
        {
//            xThrow(ERR_PARAMETER);
            return [
                'code' => 1,
                'message' => '无数据，废品可能还未入库3'
            ];
        }
        $where              = ['id'=>$wasteId];
        $info               = \App\Eloquent\Ygt\Waste::getInfo($where);
        if(!$info)
        {
            xThrow(ERR_PARAMETER,'废品信息出错');
        }
        $infoArr            = $info->toArray();
        $relateType         = $infoArr['relate_type'];//相关类型 1-材料 2-工序废品
        $relateId           = $infoArr['relate_id'];
        $infoNumber         = $infoArr['number'];
        $defaultArr         = [
            'product_name'=>'',
            'product_no'=>'',
            'is_public'=>'yes',
            'barcode'=>'',
            'warning_number'=>0,
            'full_number'=>0,
            'category_id'=>0,
            'price'=>0.00,
            'unit'=>'千克',
            'customer_id'=>0,
            'img_url'=>'',
            'seller_company_name'=>'',
            'customer_name'=>'',
            'image_path'=>'',
            'is_warning'=>0,
            'circle_front_color'=>'#FF5252',
            'circle_back_color'=>'#FFEDED',
            'ratio'=>0,
            'is_new'=>0,
            'custom_fields'=>[],
            'first_text'=>'',
            'second_text'=>'',
            'third_text'=>'',
            'custom_fields_text'=>''
        ];
        $infoArr            = array_merge($infoArr,$defaultArr);
        if($relateType==1){
            //取材料的详情
            $productId          = $relateId;
            $where              = ['ygt_product.id'=>$productId];
            $info               = Product::getJoinInfo($where,3);
            if(!$info)
            {
                xThrow(ERR_PRODUCT_NOT_EXIST);
            }
            $product            = $info->toArray();
            if(array_key_exists('seller_company_name',$product) && is_null($product['seller_company_name']))
            {
                $product['seller_company_name']   = '';
            }
            if(array_key_exists('customer_name',$product) && is_null($product['customer_name']))
            {
                $product['customer_name']           = '';
            }
            //取材料的图片
            $imgId              = $product['img_id'];
            $imgUrl             = Func::getImgUrlById($imgId);
            $product['img_url'] = $imgUrl;
            $productIdArr       = [$productId];
            $where              = ['product_id'=>['in',$productIdArr]];
            $customFieldsData   = ProductFields::getTransformListToArr($where);
            $product            = Product::addCustomFieldsToInfo($product,$customFieldsData,2);
            $infoArr            = array_merge($infoArr,$product);
        }else{
            $processWaste       = OrdertypeProcessWaste::where('id',$relateId)->first();
            if(!$processWaste)
            {
                $processWaste       = OrdertypeProcessWaste::withTrashed()->where('id',$relateId)->first();
                if(!$processWaste)
                {
                    xThrow(ERR_PARAMETER,'废品关联信息出错');
                }

                $infoArr['product_name']    = $processWaste->title.'【已删除】';

            }else{
                $infoArr['product_name']    = $processWaste->title;
            }

        }
        $infoArr['number']      = $infoNumber;
        //流水信息
        $where          = [
            'waste_id'=>$wasteId,
        ];

        if($wasteRelateType && $wasteRelateId){
            $where['type'] = $wasteRelateType;
            $where['relate_id'] = $wasteRelateId;
        }

        $lists          = WasteWater::getList($where,'',$limit,$offset)->toArray();
        //数据补充
        foreach ($lists as $tmpKey => $tmpValue){
            //来源工序，操作员，时间，工单号，
            $waterTips = $userTrueName = $time = $orderTitle = '';
            if($tmpValue['type'] == 1){
                $orderProcessId = $tmpValue['relate_id'];
                $orderProcessRow = \App\Eloquent\Ygt\OrderProcess::where(['id' => $orderProcessId])->first();
                if($orderProcessRow){
                    $orderRow = \App\Eloquent\Ygt\Order::where(['id' => $orderProcessRow['order_id']])->first();
                    $orderTitle = $orderRow['order_title'];
                    if($orderRow){
                        $orderTypeTitle = \App\Engine\OrderType::getOneValueById($orderRow['order_type'], 'title');
                        $waterTips = $orderTypeTitle.'产生';
                    }
                    $userInfo = \App\Eloquent\Ygt\DepartmentUser::getCurrentInfo($orderProcessRow['uid']);
                    if($userInfo){
                        $userTrueName = $userInfo['truename'];
                    }
                }
            }elseif($tmpValue['type'] == 2){

                $waterTips = '废料卖出';
            }

            $time = date('Y-m-d H:i:s',$tmpValue['created_at']);
            $lists[$tmpKey]['water_tips'] = $waterTips;
            $lists[$tmpKey]['user_true_name'] = $userTrueName;
            $lists[$tmpKey]['time'] = $time;
            $lists[$tmpKey]['order_title'] = $orderTitle;
        }


        $listData       = [
            'info'=>$infoArr,
            'list'=>$lists,
        ];
        $pagingData     = [
            'page' => $page,
            'pageSize' => 1,//////////////////待定
            'total' => 1,//////////////////待定
            'keyword' => ''
        ];
        return $this->pagingData($listData, $pagingData);
    }
}